<template>
  <div id="goods-manage">
    <div class="search-box">
        <el-form>
            <el-form-item label="博主名称：">
              <el-select v-model="form.xhs_blogger_id" placeholder="请选择店铺" size="small" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option v-for="(item, index) in bloggerListData" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="笔记标题：">
              <el-input placeholder="请输入笔记标题" v-model="form.title" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="search-btn" icon="el-icon-ali-search" @click="getNoticesData()">查&nbsp;询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button class="reset-btn" icon="el-icon-ali-reset" @click="resetSearchParam">重&nbsp;置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button class="reset-btn" icon="el-icon-ali-add-1" @click="isShowAddNotice = true">添加笔记</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table-box">
	  <div class="tips">*点击下面的笔记可以进行更新笔记信息</div>
      <div class="goods-list">
          <div class="img-box" v-for="(item,index) in noticesData" :key="index" >
            <i class="el-icon-error close-btn"  @click.stop="showDeleteConfirm(item.id)"></i>
            <div @click="showUpdate(item)">
              <img :src="item.img" class="img" alt="">
              <div class="text">博主昵称:{{item.name}}</div>
              <div class="text">笔记标题:{{item.title}}</div>
            </div>
          </div>

          <div class="no-data-img" v-if="noticesData.length == 0">
            <img src="../../assets/image/no-data.png" alt="">
            <div class="tips">暂无数据</div>
          </div>

      </div>

      <div class="block" style="margin: 20px 0px; text-align: right;">
      	<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
      	 :page-sizes="[10, 15, 20, 25]" :page-size="form.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>

    </div>

    <el-dialog title="更新笔记" :visible.sync="isShowDialog"  width="800px" class="goods-dialog">
       <div class="goods-info">
            <el-form ref="form" label-width="120px" class="el-form">
              <el-form-item label="笔记标题 :" prop="title">
                <el-input placeholder v-model="noticeDetail.title" class="disabled" size="small" />
              </el-form-item>

              <el-form-item label="笔记链接 :" prop="url">
                <el-input placeholder v-model="noticeDetail.url" class="disabled" size="small" />
              </el-form-item>
            </el-form>
       </div>
       <div class="goods-img-box">
           <div class="goods-img">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :action="BASE_API_URL+'baseapi/wechart/uploadMerchantPushImg'"
                :data="uploadData"
                :on-success="handleImgSuccess"
                :before-upload="beforeUploadNoticeImg">
                <img class="goods-main-img" :src="noticeDetail.img" alt="">
              </el-upload>
           </div>
       </div>
       <div class="update-btn-box">
         <div class="update-btn" @click="updateNotice">更新</div>
       </div>
    </el-dialog>

    <el-dialog title="添加笔记" :visible.sync="isShowAddNotice" :modal-append-to-body="false" width="70%" :before-close="cancelNotice">
      <div>
        <el-form ref="noticeInfo" :model="noticeInfo" :rules="noticeRules" label-width="120px" class="goods-form">

          <el-form-item label="博主昵称 :" prop="xhs_blogger_id">
            <el-select v-model="noticeInfo.xhs_blogger_id" class="form-input" placeholder="请选择博主" size="small" filterable clearable>
              <el-option v-for="(store, index) in bloggerListData" :key="index" :label="store.name" :value="store.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="笔记标题 :" prop="title">
            <el-input placeholder="请输入商品标题" v-model="noticeInfo.title" size="small" class="form-input"></el-input>
          </el-form-item>

          <el-form-item label="笔记链接 :" prop="url">
            <el-input placeholder="请输入笔记链接" v-model="noticeInfo.url" size="small" class="form-input"/>
          </el-form-item>

          <el-form-item label="上传图片 :" prop="img">
            <el-upload
              class="avatar-uploader"
              :action="BASE_API_URL+'baseapi/wechart/uploadMerchantPushImg'"
              :show-file-list="false"
              :on-success="handleSuccessNoticeImg"
              :before-upload="beforeUploadNoticeImg">
              <img v-if="noticeInfo.img" :src="noticeInfo.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </el-form-item>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddNotice = false">取 消</el-button>
        <el-button type="primary" @click="addNotice">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  apiXhsBlogger,
  apiBloggerNotices,
  apiDeleteBloggerNotices,
  apiCreateUpdateBloggerNotices
} from '../../request/api.js'

export default{
  data(){
    return {
      noticesData: [],
      bloggerListData: [],
      uploadData: {
        area: 'xhs_notice'
      },
      form: {
        token: '',
        page: 1,
        pageSize: 10,
        xhs_blogger_id: '',
        title: ''
      },
      total: 0,
      isShowDialog: false,
      noticeDetail: {},
      isShowAddNotice: false,
      noticeInfo: {
        xhs_blogger_id: "",
        url: "",
        type: 21,
        title: "",
        img: "",
        token: window.localStorage.getItem('token')
      },
      noticeRules: {
        xhs_blogger_id: [{required: true, message: "请选择博主", trigger: "blur"}],
        url: [{required: true, message: "请输入笔记链接", trigger: "blur"}],
        title: [{required: true, message: "请输入笔记标题", trigger: "blur"}],
        img: [{required: true, message: "请上传笔记主图"}]
      },
      userToken: window.localStorage.getItem('token'),
      merchantData: JSON.parse(window.localStorage.getItem('merchantConfig'))
    }
  },

  created() {
    this.form.token = this.userToken
    this.getBloggerList()
    this.getNoticesData()
  },
  methods:{
    // 新增笔记
    addNotice() {
      this.$refs["noticeInfo"].validate(valid => {
        if (valid) {
          apiCreateUpdateBloggerNotices(this.noticeInfo).then(res => {
            if (res.code == 1) {
              this.$message.success(res.msg)
              this.isShowAddNotice = false
              this.getNoticesData()
            } else {
              this.$message.error(res.msg)
            }
          }).catch(res => {
            console.log(res)
          })
        } else {
          this.$message.error("信息不完善，请先填写");
          return false
        }
      })
    },

    // 取消新增商品
    cancelNotice() {this.isShowAddNotice = false},

    handleSuccessNoticeImg(res, file) {
      this.noticeInfo.img = res.msg;
      this.$message.success("上传成功");
    },

    beforeUploadNoticeImg(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传商品图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    resetSearchParam(){
      this.form = {
        token: this.userToken,
        page: 1,
        pageSize: 10,
        productId: '',
        shopType: ''
      }
      this.getNoticesData()
    },

    showUpdate(item){
      this.noticeDetail = item
      this.noticeDetail.token = this.userToken
      this.isShowDialog = true
    },

    updateNotice(){
      apiCreateUpdateBloggerNotices( this.noticeDetail ).then(res =>{
        if (res.code == 1){
          this.isShowDialog = false
          return this.$message.success("更新成功");
        } else {
          this.isShowDialog = false
          return this.$message.success("更新失败");
        }
      }).catch(res => {
        this.isShowDialog = false
        this.$message.error(res.msg)
      })


    },

    showDeleteConfirm(id){
      this.$confirm('此操作将删除该笔记, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteNotice(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    deleteNotice(id){
      apiDeleteBloggerNotices({
        token: this.userToken,
        id: id
      }).then(res =>{
        if (res.code == 1){
          this.$message.success('删除成功');
          this.getNoticesData()
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$message.error(res.msg)
      })
    },

    getBloggerList() {
      this.$isClick(true);
      apiXhsBlogger({
        token: this.userToken
      }).then(res =>{
        this.$isClick(false);
        if (res.code == 1){
          for (var i in res.msg.merchant_shop_list) {
            this.bloggerListData.push({
              name: res.msg.merchant_shop_list[i].name,
              id: res.msg.merchant_shop_list[i].id
            })
          }
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },

    getNoticesData() {
      this.$isClick(true);
      apiBloggerNotices(this.form).then(res =>{
        this.$isClick(false);
        if (res.code == 1){
          this.noticesData = res.msg.res
          this.total = res.msg.con
        } else {
          this.$message.error(res.msg);
        }
      }).catch(res => {
        this.$isClick(false);
        this.$message.error(res.msg)
      })
    },

    handleSizeChange(val) {
      this.form.pageSize = val;
      this.getNoticesData()
    },

    handleCurrentChange(val) {
      this.form.page = val;
      this.getNoticesData()
    },

    handleImgSuccess(res, file) {
      this.noticeDetail.img = res.msg;
      this.$message.success("上传成功");
    },

    compressUpload(image) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let initSize = image.src.length
      let { width } = image, { height } = image
      canvas. width = width
      canvas.height = height
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(image, 0, 0, width, height)

      // 进行最小压缩0.1
      let compressData = canvas.toDataURL('image/jpeg', 0.1)

      // 压缩后调用方法进行base64转Blob，方法写在下边
      let blobImg = this.dataURItoBlob(compressData)
      return blobImg
    },

    /* base64转Blob对象 */
    dataURItoBlob(data) {
      let byteString;
      if(data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(data.split(',')[1])
      }else {
        byteString = unescape(data.split(',')[1])
      }
      let mimeString = data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0];
      let ia = new Uint8Array(byteString.length)
      for( let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], {type: mimeString})
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  }
}
</script>

<style lang="less">
#goods-manage {

  .table-box {
    .tips {
      color: red;
      margin-top: -16px;
      margin-bottom: 16px;
    }
    .goods-list {
      .img-box {
        display: inline-block;
        margin: 8px;
        width: 150px;
        box-shadow: 0px 0px 3px #666;
        padding: 5px;
        border-radius: 5px;
        position: relative;
        cursor: pointer;

        .close-btn {
          position: absolute;
          right: -7px;
          top: -10px;
          color: red;
          font-size: 20px;
          display: none;
        }
        //.success-btn {
        //  position: absolute;
        //  right: 7px;
        //  top: -10px;
        //  color: red;
        //  font-size: 20px;
        //  display: none;
        //}
        .text{
          font-size: 14px;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
        .delete-icon {
          color: red;
          padding: 3px;
          cursor: pointer;
        }
        .img{
          width: 150px;
          height: 150px;
        }
      }
      .img-box:hover{
        .close-btn {
          display: inline-block;
        }

      }
    }
  }
  .goods-dialog {
    .goods-info {
      display: inline-block;
      width: 500px;
      margin-right: 20px;
    }
    .goods-img-box {
      display: inline-block;
      vertical-align: top;
      .goods-img {
        width:200px;
        height: 200px;
        border: 1px solid;
        margin-top: 53px;
      }
    }
    .avatar-uploader .el-upload {
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: @themeColor;
    }
    .goods-main-img{
      width: 200px;
      height: 200px;
    }
    .update-btn-box {
      text-align: center;
      .update-btn {
        display: inline-block;
        background-color: @themeColor;
        color: #fff;
        padding: 8px 30px;
        border-radius: 5px;
        margin-top: 20px;
        cursor: pointer;
        // margin: 0 auto;
      }
    }
  }
  .no-data-img {
    text-align: center;
    margin-top: 80px;
    .tips{
      font-size: 14px;
      margin-top: 10px;
      color: @fontSubtitleColor;
    }
  }
}
</style>
